# -*- coding:UTF-8 -*-

import json
import random
# 阿里云生成域名相关SDK
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.auth.credentials import AccessKeyCredential
from aliyunsdkalidns.request.v20150109.AddDomainRecordRequest import AddDomainRecordRequest
from aliyunsdkalidns.request.v20150109.DescribeSubDomainRecordsRequest import DescribeSubDomainRecordsRequest
from aliyunsdkalidns.request.v20150109.SetDomainRecordStatusRequest import SetDomainRecordStatusRequest
from aliyunsdkalidns.request.v20150109.UpdateDomainRecordRequest import UpdateDomainRecordRequest
from aliyunsdkalidns.request.v20150109.DeleteDomainRecordRequest import DeleteDomainRecordRequest

from utils.common import setup_log
from utils.http_send import send_domain_log

logger = setup_log("domain_mgmt.log")


def client_init():
    try:
        credentials = AccessKeyCredential(
            'LTAII5qYZbJpQQai', 'Xaw9Ges85fHh2jEioZU7IVbgV32MnU')
        # use STS Token
        # credentials = StsTokenCredential('<your-access-key-id>', '<your-access-key-secret>', '<your-sts-token>')
        client = AcsClient(region_id='cn-qingdao', credential=credentials)
    except Exception as _:
        return None
    return client


def add_domain(app_name, ip):
    r_str = random.sample('zyxwvutsrqponmlkjihgfedcba', 5)
    r_str = "".join(r_str)
    rr = f"{random.randint(0, 9)}{random.randint(0, 9)}{random.randint(0, 9)}{random.randint(0, 9)}"
    rr = f"{rr}-{r_str}{random.randint(0, 9)}"
    rr = f"{app_name}-{rr}"
    client = client_init()
    if client is None:
        return False, "域名服务连接异常", "", ""

    request = AddDomainRecordRequest()
    request.set_accept_format('json')

    request.set_DomainName("aiapi.pro")
    request.set_RR(rr)  # 子域名
    request.set_Type("A")
    request.set_Value(str(ip))  # 绑定的IP

    try:
        response = client.do_action_with_exception(request)
        response = json.loads(str(response, encoding='utf-8'))
        RecordId = response['RecordId']

        response = send_domain_log(RecordId, rr, str(ip))
        return True, "ok", response.get('id', -1), f"{rr}.aiapi.pro"
    except Exception as e:
        return False, f"{e}", "", ""


def search_sub_domain(rr):
    sub_domain = str(rr)
    client = client_init()
    if client is None:
        return False, "域名服务连接异常", "", ""
    request = DescribeSubDomainRecordsRequest()
    request.set_accept_format('json')
    rr = f"{str(rr)}.aiapi.pro"

    request.set_SubDomain(str(rr))
    request.set_DomainName("aiapi.pro")
    request.set_Type("A")

    response = client.do_action_with_exception(request)
    response = json.loads(str(response, encoding='utf-8'))
    RequestId = response.get("RequestId", None)
    RecordId = ""
    status = ""
    if RequestId is None:
        return False, "", RecordId, status

    for Record in response.get("DomainRecords", {}).get("Record", []):
        if Record['RR'] == sub_domain:
            RecordId = Record['RecordId']
            status = Record['Status']

    if RecordId == "":
        return False, "", RecordId, status

    return True, RequestId, RecordId, status


def set_domain_status(RecordId, status=False):
    RecordId = str(RecordId)

    client = client_init()
    if client is None:
        return False, "域名服务连接异常", ""
    request = SetDomainRecordStatusRequest()
    request.set_accept_format('json')

    request.set_RecordId(RecordId)
    _status = "Disable"
    if status:
        _status = "Enable"
    request.set_Status(_status)

    try:
        response = client.do_action_with_exception(request)
        response = json.loads(str(response, encoding='utf-8'))
        return True, response['RecordId'], response['Status']
    except Exception as e:
        return False, f"{e}", f"{e}"


def update_domain(RecordId, rr, ip):
    client = client_init()
    if client is None:
        return False, "域名服务连接异常"
    request = UpdateDomainRecordRequest()
    request.set_accept_format('json')
    request.set_RecordId(str(RecordId))
    request.set_RR(str(rr))
    request.set_Type("A")
    request.set_Value(str(ip))
    try:
        response = client.do_action_with_exception(request)
        response = json.loads(str(response, encoding='utf-8'))
        return True, response['RecordId']
    except Exception as e:
        return False, f"{e}"


def del_domain(RecordId):
    client = client_init()
    if client is None:
        return False, "域名服务连接异常"
    request = DeleteDomainRecordRequest()
    request.set_accept_format('json')
    request.set_RecordId(str(RecordId))
    _ = client.do_action_with_exception(request)
    # python2:  print(response)
    return True, "ok"
